package pers.jason.wppm.security.core.validate.code;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import pers.jason.wppm.security.core.properties.SecurityProperties;
import pers.jason.wppm.security.core.validate.code.filter.ValidateCodeFilter;
import pers.jason.wppm.security.core.validate.code.generator.ImageCodeGenerator;
import pers.jason.wppm.security.core.validate.code.generator.SmsCodeGenerator;

/**
 * 
 * @author Jason
 * @Date 2018-11-01 15:05
 *
 */
@Component("validateCodeAuthenticationConfig")
public class ValidateCodeConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
	
	@Autowired
	private SecurityProperties securityProperties;
	
	@Autowired
	private ValidateCodeFilter validateCodeFilter;

	@Bean
	@ConditionalOnMissingBean
	public ImageCodeGenerator imageCodeGenerator() {
		ImageCodeGenerator imageCodeGenerator =  new ImageCodeGenerator();
		imageCodeGenerator.setSecurityProperties(securityProperties);
		return imageCodeGenerator;
	}
	
	
	@Bean
	@ConditionalOnMissingBean
	public SmsCodeGenerator smsCodeGenerator() {
		SmsCodeGenerator smsCodeGenerator = new SmsCodeGenerator();
		smsCodeGenerator.setSecurityProperties(securityProperties);
		return smsCodeGenerator;
	}
	
	/**
	 * 将验证码过滤器配置到security过滤器链上
	 */
	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class);
	}
	
	
	
}
